package com.project;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;

@WebServlet("/TicketApprovalServlet")
public class TicketApprovalServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 验证管理员身份
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        if (admin == null) {
            request.setAttribute("error", "请先以管理员身份登录");
            request.getRequestDispatcher("login.jsp").forward(request, response);
            return;
        }

        String requestId = request.getParameter("requestId");
        String action = request.getParameter("action");

        // 从ServletContext获取待审核列表
        List<Map<String, String>> pendingRequests = (List<Map<String, String>>) getServletContext().getAttribute("pendingTicketRequests");
        boolean result = false;

        // 查找并处理目标请求（改用迭代器避免并发修改异常）
        if (pendingRequests != null) {
            Iterator<Map<String, String>> iterator = pendingRequests.iterator();  // 使用迭代器
            while (iterator.hasNext()) {
                Map<String, String> requestMap = iterator.next();
                if (requestMap.get("id").equals(requestId)) {
                    // 调用Admin方法更新数据库
                    if ("approve".equals(action)) {
                        // 构造Adjust_ticket需要的参数：[ticketId, oid, uid, seat, state]
                        List<String> updateParams = new ArrayList<>();
                        updateParams.add(requestMap.get("ticketId"));  // ticketId（主键）
                        updateParams.add(requestMap.get("oid"));
                        updateParams.add(requestMap.get("uid"));
                        updateParams.add(requestMap.get("seat"));
                        result = admin.Adjust_ticket(updateParams);
                    } else if ("reject".equals(action)) {
                        result = true;  // 拒绝操作默认成功
                    }
                    iterator.remove();  // 安全移除元素
                    break;
                }
            }
            // 更新ServletContext中的列表
            getServletContext().setAttribute("pendingTicketRequests", pendingRequests);
        }

        // 添加操作结果提示（使用session传递）
        String message = result ? "操作成功" : "操作失败，请重试";
        request.getSession().setAttribute("approvalMessage", message);

        response.sendRedirect("handleTickets.jsp");  // 刷新处理页面
    }
}